package com.hmall.order.config;

import org.springframework.stereotype.Component;

public class SnowflakeIdGenerator {

    private long workerId; // 工作机器ID
    private long datacenterId; // 数据中心ID
    private long sequence = 0L; // 毫秒内序列

    // 时间戳基础值
    private final long twepoch = 1288834974657L;
    private final long workerIdBits = 5L; // 机器ID位数
    private final long datacenterIdBits = 5L; // 数据中心ID位数
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 最大机器ID
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 最大数据中心ID
    private final long sequenceBits = 12L; // 每毫秒内产生的序列数
    private final long workerIdShift = sequenceBits; // 机器ID左移位数
    private final long datacenterIdShift = sequenceBits + workerIdBits; // 数据中心ID左移位数
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // 时间戳左移位数
    private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 生成序列的掩码
    private long lastTimestamp = -1L; // 上次生成ID的时间戳

    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        // 检查workerId和datacenterId是否超过最大值
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    // 生成ID方法
    public synchronized long nextId() {
        long timestamp = timeGen();

        // 如果当前时间小于上次生成ID的时间戳，说明系统时钟回退过，此时要抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        // 如果是同一时间内生成的ID，则自增序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        // 如果是新的时间戳，序列重置为0
        else {
            sequence = 0L;
        }

        // 保存上次生成ID的时间戳
        lastTimestamp = timestamp;

        // 返回生成的ID
        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    // 获取下一个时间戳
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    // 获取当前时间的时间戳
    protected long timeGen() {
        return System.currentTimeMillis();
    }
}